package com.ouc.yyi.config.shiro;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

@Configuration
public class ShiroConfig {

   @Bean("shiroFilter")
   public ShiroFilterFactoryBean shiroFilter(@Qualifier("securityManager") SecurityManager manager){
       ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
       bean.setSecurityManager(manager);

       //设置登录的url
       bean.setLoginUrl("/login");
       //登陆成功跳转的url
       bean.setSuccessUrl("/index");
       //没有权限跳转的url
       bean.setUnauthorizedUrl("/unauthorized");
       //核心的
       LinkedHashMap<String,String> filterChainDefinitionMap = new LinkedHashMap<>();
       filterChainDefinitionMap.put("/index","authc");//配置需要校验的
       filterChainDefinitionMap.put("/static/**", "anon");
       filterChainDefinitionMap.put("/login","anon");
      // filterChainDefinitionMap.put("/test/**","anon");
       //只要登陆就可以访问其他界面
      // filterChainDefinitionMap.put("/loginUser","anon");
       //只允许角色为admin的访问
       //filterChainDefinitionMap.put("/admin","roles[admin]");
       //拦截所有的
       //filterChainDefinitionMap.put("/**","user");


       bean.setFilterChainDefinitionMap(filterChainDefinitionMap);
       return bean;
   }

    @Bean("securityManager")
    public SecurityManager securityManager(@Qualifier("authRealm") AuthRealm authRealm){
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(authRealm);
        return manager;
    }


    @Bean("authRealm")
    public AuthRealm authRealm(@Qualifier("credentialMatcher") CredentialMatcher matcher){
        AuthRealm authRealm = new AuthRealm();
        //给出密码比较器
        authRealm.setCredentialsMatcher(matcher);
        return  authRealm;
    }
    //定义密码匹配的规则
    @Bean("credentialMatcher")
    public  CredentialMatcher credentialMatcher(){
        return new CredentialMatcher();
    }

    //shiro跟spring之间的关联
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("securityManager") SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }
    @Bean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
       DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator();
       creator.setProxyTargetClass(true);
       return creator;
    }


}
